package edu.uwm.cs552;

import java.awt.Graphics;
import java.awt.Point;
import java.awt.image.BufferedImage;

import javax.swing.ImageIcon;

public class BarrierDraw implements HexBoardEditAction {

	public static final double BOUND = 0.5; // only considers points 50% of max distance from edge
	
	private Barrier barrier;
	
	public BarrierDraw(Barrier b) {
		barrier = b;
	}
	
	public void apply(HexBoard hexBoard, Point p, double scale) {
		HexEdge e = HexEdge.fromPoint(p, scale, BOUND);
		if (e == null) return;
		if (barrier == null) hexBoard.removeBarrier(e);
		else hexBoard.putBarrier(e, barrier);
	}

	public String getLabel() {
		if (barrier == null) return "[Erase barrier]";
		else return barrier.name();
	}

	public ImageIcon getIcon() {
		int i = barrier == null ? Barrier.values().length : barrier.ordinal();
		return getBarrierIcons()[i];
	}

	private static ImageIcon[] icons;
	
	/**
	 * Return the (singleton) array of icons for barriers indexed by barrier ordinal.
	 * With one extra item at the end for blank icon.
	 * @return
	 */
	static ImageIcon[] getBarrierIcons() {
		if (icons == null) {
			ImageIcon[] result = new ImageIcon[Terrain.values().length+1];
			for (int i=0; i < result.length; ++i) {
				BufferedImage im = new BufferedImage(ICON_SIZE,ICON_SIZE, BufferedImage.TYPE_INT_ARGB);
				Graphics g = im.getGraphics();
				g.translate(0, ICON_SIZE/2);
				if (i < Barrier.values().length) {
					Barrier.values()[i].draw(g, new HexEdge(HexCoordinate.ORIGIN, HexDirection.EAST), ICON_SIZE, true);
				}
				result[i] = new ImageIcon(im);
			}
			icons = result;
		}
		return icons;
	}
}
